/*
 * @Author: dfh
 * @Date: 2024-09-24 09:45:05
 * @LastEditors: dfh
 * @Modified By: dfh
 * @describe: 
 */
import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useHomeStore = defineStore('homeStore', () => {
    //桌位号
    const sitNum = ref(1);
    //当前左侧菜单选择的是菜品还是套餐
    const type = ref(1);
    const cartInfo = ref([]);
    const totalNum = ref(0);
    const totalPrice = ref(0);

    const setSitNum = (num) => {
        sitNum.value = num;
    }

    const setType = (val)=>{
        type.value = val;
    }

    const currentFlavorsItem = ref({
        name: '',
        flavors: [],
        price: 0
    });

    //添加购物车
    const addCartInfo = (item, type) => {
        const { id } = item;
        const cartItem = cartInfo.value.find(item => item.id === id);
        if (cartItem) {
            cartInfo.value = cartInfo.value.map(item => {
                if (item.id == id) return { ...item, num: type == 'add' ? item.num + 1 : item.num - 1 };
                return item;
            });
        } else {
            cartInfo.value = [{ ...item, num: 1 }, ...cartInfo.value]
        }
        let total_num = 0, total_price = 0;
        cartInfo.value.forEach(item => {
            total_num += item.num;
            total_price += (item.price || 0) * item.num;
        })
        totalNum.value = total_num;
        totalPrice.value = total_price / 100;
    }

    //选择规则
    const onFlavorClick = (item, num) => {

        addCartInfo(item, num);
    }

    //打开flavors选择
    const openFlavorSelect = (item, num) => {
        currentFlavorsItem.value = item;
    }

    //清除选择的flavors
    const clearFlavors = () => {
        currentFlavorsItem.value = {
            name: '',
            flavors: [],
            price: 0
        }
    }


    return {
        sitNum,
        setSitNum,
        type,
        setType,
        cartInfo,
        totalNum,
        totalPrice,
        currentFlavorsItem,
        addCartInfo,
        openFlavorSelect,
        onFlavorClick,
        clearFlavors
    }
})